package com.zlq.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

//统计网站在线人数：统计session
public class OnlineCountListener implements HttpSessionListener {

    //创建session监听
    //一旦创建session就会触发一次这个事件
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
        //Integer user_count = (Integer) servletContext.getAttribute("User_Count");
        if (onlineCount==null){
            onlineCount = new Integer(1);
        }else{
            int count = onlineCount.intValue();
            onlineCount = new Integer(count + 1);
        }
//        if (servletContext.getAttribute("User_Count")!=null){
//            int count = user_count.intValue();
//            user_count = new Integer(count + 1);
//        }else{
//            user_count = new Integer(0);
//        }

        servletContext.setAttribute("OnlineCount",onlineCount);
        //servletContext.setAttribute("User_Count",user_count);
    }

    //销毁session监听
    //一旦销毁session就会触发一次这个事件
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {

        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
        if (onlineCount==null){
            onlineCount = new Integer(0);
        }else{
            int count = onlineCount.intValue();
            onlineCount = new Integer(count - 1);
        }
        servletContext.setAttribute("OnlineCount",onlineCount);
    }
}

/*
Session销毁：
1、手动销毁 getSession().invalidate();
2、自动销毁 去web.xml中配置销毁时间
 */


















